import { defineStore } from "pinia";

export interface ILoginUserModel {
  userInfo: {
    userId: string;
    phone: string;
    username: string;
    avatar: string;
    nickname: string;
    openid: string;
  };
  token: string;
  isLogin: true;
}

export interface IEmptyUserModel {
  isLogin: false;
}

type TUserModel = ILoginUserModel | IEmptyUserModel;

export const useUserStore = defineStore("user", () => {
  const user = ref<TUserModel>({ isLogin: false });
  const token = useStorage("USER_TOKEN", "");
  const openid = useStorage("USER_OPENID", "");

  watch(
    () => user.value,
    (newValue) => {
      if (newValue.isLogin) {
        token.value = newValue.token;
        openid.value = newValue.userInfo.openid;
      }
    }
  );

  return {
    user,
    token,
    openid
  };
});
